package com.briup.pts.service.impl;

import com.briup.pts.config.exception.ServiceException;
import com.briup.pts.config.response.ResultCode;
import com.briup.pts.domain.bean.Hurdles;
import com.briup.pts.domain.vo.HurdlesVO;
import com.briup.pts.mapper.HurdlesMapper;
import com.briup.pts.service.HurdlesService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class HurdlesServiceImpl implements HurdlesService {

    private final HurdlesMapper hurdlesMapper;

    @Override
    public void changeSavedNum(String hId, Integer changeNum) {
        // 参数校验
        if (hId == null || changeNum == 0) {
            return;
        }

        // 根据id查询栏圈信息
        Hurdles hurdles = hurdlesMapper.queryById(hId);

        // 处理减少存量的情况（移出）
        if (changeNum < 0) {
            handleDecreaseSaved(hurdles, changeNum);
            return;
        }

        // 处理增加存量的情况（移入）
        handleIncreaseSaved(hurdles, changeNum);
    }

    @Override
    public List<HurdlesVO> queryAll() {
        return hurdlesMapper.queryAll();
    }

    private void handleDecreaseSaved(Hurdles hurdles, Integer changeNum) {
        // 栏圈不存在时直接返回
        if (hurdles == null) {
            return;
        }

        int newSaved = hurdles.getHSaved() + changeNum;
        // 检查是否超出承载范围
        if (newSaved < 0) {
            throw new ServiceException(ResultCode.HURDLES_SAVED_IS_EMPTY);
        }

        String fullFlag = newSaved < hurdles.getHMax() ? "未满" : "已满";
        hurdlesMapper.updateSaved(hurdles.getHId(), newSaved, fullFlag);
    }

    private void handleIncreaseSaved(Hurdles hurdles, Integer changeNum) {
        // 检查栏圈是否存在且可用
        if (hurdles == null || !"可用".equals(hurdles.getHEnable())) {
            throw new ServiceException(ResultCode.HURDLES_IS_NOT_EXISTS);
        }

        int newSaved = hurdles.getHSaved() + changeNum;
        // 检查是否超出最大容量
        if (newSaved > hurdles.getHMax()) {
            throw new ServiceException(ResultCode.HURDLES_SAVED_IS_FULLED);
        }

        String fullFlag = newSaved == hurdles.getHMax() ? "已满" : "未满";
        hurdlesMapper.updateSaved(hurdles.getHId(), newSaved, fullFlag);
    }
}
